package service

import (
	"cgs-server/server/model"
	"cgs-server/server/store"
	"go.mongodb.org/mongo-driver/bson"
)

type WorkflowSrv interface {
	// Save 保存工作流
	Save(mdl *model.Workflow, user *model.User) error

	// Get 根据 ID 查找工作流
	Get(mdl *model.Workflow, user *model.User) (*model.Workflow, error)

	// Update 更新 工作流
	Update(mdl *model.Workflow, user *model.User) error

	// Delete 删除工作流
	Delete(mdl *model.Workflow, user *model.User) error

	// List 列表
	List(mdl *model.DataUserModel) (interface{}, error)
}

type workflowSrv struct {
	store store.Factory
}

func (w *workflowSrv) Save(mdl *model.Workflow, user *model.User) error {
	return w.store.Workflow().Save(mdl, user)
}

func (w *workflowSrv) Get(mdl *model.Workflow, user *model.User) (*model.Workflow, error) {
	return w.store.Workflow().Get(mdl, user)
}

func (w *workflowSrv) Update(mdl *model.Workflow, user *model.User) error {
	return w.store.Workflow().Update(mdl, user)
}

func (w *workflowSrv) Delete(mdl *model.Workflow, user *model.User) error {
	return w.store.Workflow().Delete(mdl, user)
}

func (w *workflowSrv) List(mdl *model.DataUserModel) (interface{}, error) {
	workflow := mdl.Data.(*model.Workflow)
	mdl.Filter = &bson.M{
		"category": workflow.Category,
	}

	data, err := w.store.Workflow().List(mdl)
	if err != nil {
		return nil, err
	}
	count, err := w.store.Workflow().Count(*mdl.Filter)
	if err != nil {
		return nil, err
	}

	return bson.M{
		"current": mdl.Page.Current,
		"size": mdl.Page.Size,
		"total": count,
		"data": data,
	}, nil
}

func newWorkflowSrv(s *service) WorkflowSrv {
	return &workflowSrv{
		store: s.store,
	}
}
